package com.cy.module;

import com.alibaba.fastjson.JSONObject;
import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.LicenseToken;
import com.cy.model.Order;
import com.cy.model.PackageInfo;
import com.cy.model.User;
import com.cy.utils.excel.ExcelBean;
import com.cy.utils.excel.ExcelTools;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/order")
public class OrderController extends WebApiController {
    @Override
    public void index() {
        Order order = getModel(Order.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Map<String, String[]> parasMap = getParaMap();
        if (null != parasMap){
            String start ;
            if(null != parasMap.get("start_time")){
                start = parasMap.get("start_time")[0];
                if (StringUtils.isNotBlank(start))
                    order.put("start",start);
            }
            String end;
            if (null != parasMap.get("end_time")){
                end = parasMap.get("end_time")[0];
                if (StringUtils.isNotBlank(end))
                    order.put("end",end);
            }
        }
        Page<Order> orderPage = Order.dao.paginate(page, pageSize, Order.SELECT_ALL, order);
        renderBuiPage(orderPage, 200);
    }

    public void getTokenByOrder() {
        Order order = getModel(Order.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");

        Map<String, String[]> parasMap = getParaMap();

        if (null != parasMap){
            String start = null ;
            if(null != parasMap.get("start_time")){
                start = parasMap.get("start_time")[0];
            }
            String end = null;
            if (null != parasMap.get("end_time")){
                end = parasMap.get("end_time")[0];
            }
            if (StringUtils.isNotBlank(start)){
                order.put("start",start);
            }
            if (StringUtils.isNotBlank(end)){
                order.put("end",end);
            }

            String tokenId = null;
            if (null != parasMap.get("token_id")){
                tokenId = parasMap.get("token_id")[0];
            }
            if (StringUtils.isNotBlank(tokenId)){
                order.put("token_id",tokenId);
            }

            String tokenCode = null;
            if (null != parasMap.get("token_code")){
                tokenCode = parasMap.get("token_code")[0];
            }
            if (StringUtils.isNotBlank(tokenCode)){
                order.put("token_code",tokenCode);
            }

        }
        String fromWhere = null;
        if(null != order.get("token_id") || null != order.get("token_code")){
            fromWhere = " ,user u , license_token lt WHERE cy_order.order_id = lt.order_id and cy_order.user_id = u.user_id ";
        }

        Page<Order> orderPage = Order.dao.findOrderAndTokenList(page, pageSize, fromWhere, order);
        renderBuiPage(orderPage, 200);
    }

    public void queryOrderByExpress(){
        Order order = getModel(Order.class);
        if (StringUtils.isNotBlank(order.getExpressNo())){
            String select = Order.SELECT_ALL + ",pi.color";
            String fromWhere = ", license_token lt , package_info pi WHERE license_token_id = lt.token_id and product_no = pi.pack_tag ";
            List<Order> orders = Order.dao.findOrderInfoByExpress(order,select,fromWhere);

            renderBuiPage(new Page(orders,1,30,0,0), 200);
            return;
        }
        renderBuiPage(new Page(new ArrayList(),1,30,0,0), 200);
    }
      
    public void queryOrderByOrderNo(){
        Order order = getModel(Order.class);
        if (StringUtils.isNotBlank(order.getOrderNo())){
//            String select = Order.SELECT_ALL + ",pi.color";
//            String fromWhere = ", package_info pi WHERE product_no = pi.pack_tag ";
            List<LicenseToken> orders = LicenseToken.dao.findByOrderNO(order.getOrderNo());

            renderBuiPage(new Page(orders,1,30,0,0), 200);
            return;
        }
        renderBuiPage(new Page(new ArrayList(),1,30,0,0), 200);
    }

    @Override
    public void show() {

    }

   @Override
    public void update() {
        int id = getParaToInt();
        Order tempOrder = getModel(Order.class);
        Order order = Order.dao.findById(id);
        order.cover(tempOrder);
        if (order.update()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void save() {
        Order order = getModel(Order.class);
        order.setCreateTime(new Date());
        if (order.save()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void delete() {
        String[] ids = getPara().split("-");
        for (String id : ids) {
            Order.dao.deleteById(id);
        }
        renderSuccess();
    }

    public void importOrdersView(){

        String filePath = getPara("path");
        File file = null;
        try{
            file = new File(filePath);
        }catch (NullPointerException e){
            renderJson();
        }

        ExcelBean excelBean = new ExcelBean();
        excelBean.setSheetNo(0);
        excelBean.setStart(1);
        excelBean.setEnd(0);
        List<List<Object>> excel = ExcelTools.readSheet(file, excelBean);
        renderJson(excel);
    }

    public void claimOrder(){
        JSONObject json = new JSONObject();
        Map<String, String []> paraMap = getParaMap();
        String orderNo = null,
               oldPhone = null,
               mobile = null;
        if (null != paraMap.get("userPhone") && null != paraMap.get("claimOriginalOrder")&& null != paraMap.get("oldUserPhone")){
            orderNo = paraMap.get("claimOriginalOrder")[0];
            mobile = paraMap.get("userPhone")[0];
            oldPhone = paraMap.get("oldUserPhone")[0];
        }else{
            renderRetCode(EnumConst.RetCode.PARAMETER_IS_NULL);
            return;
        }

        User user = User.dao.findByMobile(mobile);
        if (user != null){
            if (user.getStatus() == 1){
                User oldUser = User.dao.findByMobile(oldPhone);
                if (oldUser.getStatus() ==  0){
                    StringBuilder sb = new StringBuilder();
                    sb.append(oldUser.getRemark());
                    sb.append(" ").append(new Date()).append("被账号:").append(user.getUserId()).append("-").append(user.getMobile()).append("认领;");
                    oldUser.setRemark(sb.toString());
                    if(oldUser.update()){
                        List<Order> orderList = Order.dao.findByOriginalOrderNo(orderNo);
                        for (Order o : orderList){
                            o.setUserId(user.getUserId()).update();
                        }
                    }else {
                        renderRetCode(EnumConst.RetCode.SYSTEM_ERROR);
                        return;
                    }

                }else {
                    json.put("status",300018);
                    json.put("msg","旧用户已经激活，不能被认领");
                }

            }else{
                renderRetCode(EnumConst.RetCode.USER_NOTACTIVATE);
                return;
            }

        }else{
            renderRetCode(EnumConst.RetCode.USER_NOTEXISTS);
            return;
        }

        json.put("status",1);
        json.put("msg","success");
        renderJson(json);
    }

    public void getProduct(){
        String productNo = getPara("product_no");
        PackageInfo info = PackageInfo.dao.findByTag(productNo);
        renderJson(info);
    }
}
